#include <iostream>
#include <pthread.h>
#include <signal.h>
#include "Log.hpp"
#include "Socket.hpp"
#include "Task.hpp"
#include "ThreadPool.hpp"
#include "Protocol.hpp"

static const int defaultport = 8081; //默认端口，可更改

class HttpServer
{
public:
    HttpServer(int _port = defaultport): port(_port),stop(false)
        {}
    void InitServer()
    {
        //信号SIGPIPE需要进行忽略，如果不忽略，在写入时候，可能直接崩溃server
        signal(SIGPIPE, SIG_IGN); 
    }
    void Loop()
    {
        Socket *tsvr = Socket::getinstance(port); //获取单例对象
        LOG(INFO, "Loop begin");
        while(!stop)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sock = accept(tsvr->Sock(), (struct sockaddr*)&peer, &len); //获取连接
            
            if(sock < 0) continue;
            // int* _sock = new int(sock);
            // pthread_t tid;
            // pthread_create(&tid, nullptr, CallBack::HandlerRequest, (void*)_sock);
            // pthread_detach(tid);
            
            Task task(sock);
            ThreadPool::GetInstance()->PushTask(task);
        }
    }

private:
    int port;
    bool stop;
};
